/**
* Switches the translation grid between fullscreen/condensed
* @param linkButton A DOM object of the link which changes the view
*/
function toggleFullWindow(linkButton) {
    var fullsizeDiv = document.getElementById(GetClientId("fullsizeholder"));
    if (typeof (fullsizeDiv) != "undefined") {
        if (fullsizeDiv.className.toLowerCase() == "ssfullsize") {
            fullsizeDiv.className = "ssContracted";
            linkButton.className = "lnkExpand";
            linkButton.childNodes[0].nodeValue = "Expand to fill window";
        } else {
            fullsizeDiv.className = "ssFullSize";
            linkButton.className = "lnkContract";
            linkButton.childNodes[0].nodeValue = "Contract to normal size";
        }
    }
    return false;
}

/**
* Returns a JSON request string for use when requesting a translation
* @param textBoxId The ID of the textbox containing the translation to find
* @param requestLanguage The language of the text in the textbox ( language-COUNTRY )
*/
function getTranslationData(textBoxId, requestLanguage) {
    var request = { type: "request", language: requestLanguage, translation: encodeURI(document.getElementById(textBoxId).value) };
    return JSON.stringify(request);
}

/**
* Selects a translation when a list item is clicked
* @param selectedTranslation The ID of the translation which was selected
* @param tableCell The ID of the cell containing the results div
* @param addTranslation True if this textbox is located on the add translation form (table structure is different)
*/
function selectTranslation(selectedTranslation, tableCell, addTranslation) {
    var cbo;
    if (addTranslation) {
        cbo = $("#" + GetClientId("cboAddTranslationId"));
    } else {
        var parent = $("#" + tableCell).parent();
        cbo = parent.find("td:eq(3) select");
    }
    cbo.find("option").removeAttr("selected");
    cbo.find("option[value=" + selectedTranslation + "]").attr("selected", "selected");
    cbo.change();
}

/**
* Used by the translation finder
*/
function target(event, parentTag) {
    var element = event.target;
    while (element && element.tagName != parentTag) {
        element = element.parentNode;
    }
    if (!element) { // IE fix
        return [];
    }
    return element;
}

/**
* AJAX callback which shows a list of matching translations in the specified cell/div (determined by the tagName of the element)
* @param jsonResponse The JSON response received from the server
* @param containerCell The ID of the <td> element containing the textbox
* @param addTranslation True if this textbox is located on the add translation form (table structure is different)
*/
function showMatchingTranslations(jsonResponse, containerCell, addTranslation) {
    var response = JSON.parse(jsonResponse).d;
    var active = -1;
    var parentCell = $("#" + containerCell);
    parentCell.find("#ajax-" + containerCell).remove();
    var txtBox;
    if (addTranslation) {
        txtBox = parentCell.parent().find("td:eq(1) textarea");
    } else {
        txtBox = parentCell.find("textarea");
    }
    txtBox.keyup(function(event) {
              if (event.keyCode == 27) { // ESC
                  $("#" + containerCell + "results").remove();
              }
          })
          .focus();
    if (!$.browser.msie) {
        txtBox.bind("focus", function() {
            $("#" + containerCell + "results").remove();
        });
    }
    var list = $("<ul/>");
    var element = $("<div/>")
        .addClass("find_results")
        .attr("id", containerCell + "results")
        .mouseover(function(event) {
            if (target(event, "LI").nodeName && target(event, "LI").nodeName.toUpperCase() == 'LI') {
                active = $("li", list).removeClass("find_over").index(target(event, "LI"));
                $(target(event, "LI")).addClass("find_over");
            }
        })
        .appendTo(parentCell);
    if (addTranslation) {
        var parentOffset = parentCell.offset();
        element.css({
            position: "absolute",
            top: parentOffset.top,
            left: parentOffset.left + 24,
            width: parentCell.width() - 20
        });
    } else {
        var txtOffset = txtBox.offset();
        element.css({
            position: "absolute",
            top: txtOffset.top + txtBox.height() + 32,
            left: txtOffset.left,
            width: parentCell.width() - 10
        });
    }
    var elementsAdded;
    var result;
    for (elementsAdded = 0; elementsAdded < response.length; elementsAdded++) {
        result = response[elementsAdded];
        var li = $("<li/>")
            .attr("value", decodeURI(result.ID))
            .data("title", unescape(decodeURI(result.Comment)).replace(/\+/g, " "))
            .html(unescape(decodeURI(result.Text)).replace(/\+/g, " "))
            .addClass(elementsAdded % 2 === 0 ? "find_even" : "find_odd")
            .click(function(event) {
                $(target(event), "LI").addClass("find_active");
                $("#" + containerCell + "results").remove();
                selectTranslation($(this).attr("value"), containerCell, addTranslation);
            }).mouseout(function() {
                $(this).removeClass("find_over");
            })
            .appendTo(list)[0];
    }
    if (elementsAdded > 0) {
        list.appendTo(element);
    } else {
        element.html("<p>No similar translations</p>")
               .fadeOut(4000);
    }
}
